package lj.courseinterect.rest.resources;

import lj.courseinterect.dao.i.StudentDao;
import lj.courseinterect.dao.i.TeacherDao;
import lj.courseinterect.entity.Student;
import lj.courseinterect.entity.Teacher;
import lj.courseinterect.transfer.OperationTransfer;
import lj.courseinterect.transfer.StudentTransfer;
import lj.courseinterect.transfer.TeacherTransfer;
import lj.courseinterect.transfer.TokenTransfer;
import lj.courseinterect.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;


@Component
@Path("/{a:tea|stu}/teachers")
public class TeacherResource
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private TeacherDao teacherDao;

	@Autowired
	@Qualifier("teacherAuthenticationManager")
	private AuthenticationManager authManager;

    /**
     * filter调用获得用户信息
     * @return 用户中介信息
     */
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Teacher getTeacher()
	{
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof String && ((String) principal).equals("anonymousUser")) {
            return null;
        }
        UserDetails userDetails = (UserDetails) principal;
        Teacher teacher = teacherDao.findByTeaNum(userDetails.getUsername());
        teacher.setTeaPwd("");

        return teacher;
	}

    /**
     * filter调用获得用户信息
     * @return 用户中介信息
     */
    @GET
    @Path("gettea/{teaId: [0-9]*$}")
    @Produces(MediaType.APPLICATION_JSON)
    public Teacher getTeacherById(@PathParam("teaId") Long teaId)
    {
        Teacher teacher = teacherDao.find(teaId);
        teacher.setTeaPwd("");

        return teacher;
    }

	@Path("authenticate")
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	public OperationTransfer<TokenTransfer> authenticate(@FormParam("teaNum") String teaNum, @FormParam("teaPwd") String teaPwd)
	{
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(teaNum, teaPwd);
        try{
            Authentication authentication = this.authManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);

            UserDetails userDetails = this.teacherDao.loadUserByUsername(teaNum);
            return new OperationTransfer<TokenTransfer>(true, "登陆成功",new TokenTransfer(TokenUtils.createToken(userDetails)));
        } catch (Exception ex){
            return new OperationTransfer<TokenTransfer>(false, "登陆失败");
        }
	}


    /**
     * 根据信息获取roles
     * @param userDetails 用户信息
     * @return 权限
     */
	private Map<String, Boolean> createRoleMap(UserDetails userDetails)
	{
		Map<String, Boolean> roles = new HashMap<String, Boolean>();
		for (GrantedAuthority authority : userDetails.getAuthorities()) {
			roles.put(authority.getAuthority(), Boolean.TRUE);
		}

		return roles;
	}

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public OperationTransfer create(Teacher teacher)
    {
        this.logger.info("create(): " + teacher);

        teacher.addRole("teacher");
        teacher.addRole("student");
        teacher.setTeaPwd(passwordEncoder.encode(teacher.getTeaPwd()));

        OperationTransfer operationTransfer;
        teacher.setTeaState(Teacher.TeaState.NORMAL);
        if(this.teacherDao.findByTeaNum(teacher.getTeaNum()) == null){
            try{
                this.teacherDao.save(teacher);
                operationTransfer = new OperationTransfer(true, "创建用户成功");
            } catch (Exception ex){
                operationTransfer = new OperationTransfer(false, "数据库操作失败");
            }
        } else {
            operationTransfer = new OperationTransfer(false, "用户已存在");
        }

        this.logger.info("create(): " + operationTransfer.toString());
        return operationTransfer;
    }

    public TeacherDao getTeacherDao() {
        return teacherDao;
    }

    public void setTeacherDao(TeacherDao teacherDao) {
        this.teacherDao = teacherDao;
    }
}